import axios from "axios";
import { Message } from 'element-ui';

const instance = axios.create({
    timeout: 12000,
    withCredentials: true,
    baseURL: 'http://car-api.shop2023.top'
});

// 添加请求拦截器
instance.interceptors.request.use(
    function (config) {
        const adminToken = localStorage.getItem("AdminToken");
        if (adminToken) {
            config.headers.adminToken = adminToken;
        }
        return config;
    },
    function (error) {
        // 对请求错误做些什么
        return Promise.reject(error);
    }
);

// 添加响应拦截器
instance.interceptors.response.use(
    function (response) {
        const { code, message } = response.data;
        if (code == 500) {
            Message.error(message);
            return Promise.reject(response.data);
        }
        if (code == 401) {
          localStorage.removeItem("AdminToken");
          Message.error("未授权或登录已过期，请重新登录");
          window.location.href = '/admin/login';
      }
        return response.data;
    },
    function (error) {
        Message.error(error?.response?.data?.message || "连接服务器异常：" + error.message || "连接服务器异常，请检查网络");
        return Promise.reject(error);
    }
);

export default instance;